<template>
  <div class="jksb-container">
    <ComOpenlayersMap ref="map" @mapInited="mapInited"></ComOpenlayersMap>
    <!-- 标题 -->
    <div class="navbar" :style="{ position: 'absolute', top: statusBarHeight + 'px', left: 0, right: 0 }">
      <van-image
        width="20px"
        height="20px"
        fit="contain"
        :src="require('../../assets/ic_arrow_left_white.png')"
        @click="goBack" />
      <span class="navbar-title">监控设备</span>
      <span class="navbar-right-text" @click="toStatistics">&nbsp;&nbsp;</span>
    </div>
    <div class="top-left">
      <div class="btn-icon-group">
        <div class="btn-icon" @click="openJKList">
          <van-image
            width="1rem"
            height="1rem"
            fit="contain"
            :src="require('../../assets/map_btn_list.png')"
            style="padding: 0.125rem" />
          <div class="icon-name">监控列表</div>
        </div>
      </div>
    </div>
    <div class="top-right">
      <div class="btn-icon-group">
        <van-popover v-model="showLayerPopover" trigger="click" placement="left-start" @open="openLayerPopover">
          <div class="layer-box">
            <van-image
              class="layer-yx"
              width="2.5rem"
              height="2.5rem"
              fit="contain"
              :src="require(layerType == 'YX' ? '../../assets/ic_yx_selected.png' : '../../assets/ic_yx_default.png')"
              @click="changeBaseLayer('YX')" />
            <van-image
              class="layer-sl"
              width="2.5rem"
              height="2.5rem"
              fit="contain"
              :src="require(layerType == 'SL' ? '../../assets/ic_sl_selected.png' : '../../assets/ic_sl_default.png')"
              @click="changeBaseLayer('SL')" />
          </div>
          <template #reference>
            <div class="btn-icon" @click="tcthShow = true">
              <van-image width="1.25rem" height="1.25rem" fit="contain" :src="require('../../assets/layer.png')" />
              <div class="icon-name">切换图层</div>
            </div>
          </template>
        </van-popover>
      </div>
    </div>
    <div class="left-bottom">
      <div class="btn-icon-group">
        <div class="btn-icon" @click="jurisdiction">
          <van-image width="1.25rem" height="1.25rem" fit="contain" :src="require('../../assets/jurisdiction.png')" />
          <div class="icon-name">我的辖区</div>
        </div>
      </div>
    </div>
    <div class="right-bottom">
      <div class="btn-icon-group">
        <div class="btn-icon" @click="positionSelf">
          <van-image width="1.25rem" height="1.25rem" fit="contain" :src="require('../../assets/myposition.png')" />
          <div class="icon-name">我的位置</div>
        </div>
      </div>
    </div>
    <!-- 地图监控数量聚合模板 -->
    <div v-for="item in jkList" :key="item.xzqdm" :id="`region-${item.xzqdm}`" class="region-container">
      <!-- 左侧图片 -->
      <img class="region-icon" :src="require('../../assets/map-monitoring.png')" />
      <!-- 右侧文本信息 -->
      <div class="region-text-container flexY flex1">
        <div class="region-xzqmc">{{ item.xzqmc }}</div>
        <div class="region-count">{{ item.counts }}</div>
      </div>
    </div>
    <!-- 重叠图斑 选择图斑弹窗 -->
    <van-dialog
      v-model="showJKTBDialog"
      title="选择目标监控设备（单选）"
      show-cancel-button
      confirm-button-text="确认"
      @confirm="onJKConfirm">
      <van-radio-group v-model="currentJKTbbsm" style="height: 20rem; overflow: scroll">
        <van-radio
          style="padding: 0.5rem 1rem; word-break: break-all"
          :name="item.cameraindexcode"
          v-for="item in chooseJKFeatures"
          :key="item.cameraindexcode"
          shape="square">
          {{ item.cameraname }}
        </van-radio>
      </van-radio-group>
    </van-dialog>
    <!-- 矿山列表弹窗 -->
    <van-popup
      v-model="isShowKSListPopup"
      position="left"
      :style="{ width: '70%', height: '100%', paddingTop: `${statusBarHeight}px`, boxSizing: 'border-box' }">
      <van-collapse v-model="jkListActiveNames" accordion>
        <van-collapse-item
          :icon="jkListActiveNames.includes(xzqItem.xzqdm) ? expandImg : collapseImg"
          :title="xzqItem.xzqmc"
          :name="xzqItem.xzqdm"
          :value="xzqItem.counts"
          v-for="xzqItem in jkList"
          :key="xzqItem.xzqdm">
          <van-collapse v-model="companyListActiveNames" accordion>
            <van-collapse-item
              class="company-item"
              :icon="companyListActiveNames.includes(companyItem.companyname) ? expandImg : collapseImg"
              :title="companyItem.companyname"
              :name="companyItem.companyname"
              :value="companyItem.counts"
              v-for="companyItem in xzqItem.children"
              :key="companyItem.companyname">
              <div
                class="jk-item"
                v-for="jkItem in companyItem.children"
                :key="jkItem.cameraindexcode"
                @click="jkItemClick(jkItem)">
                <span class="jk-item-name">{{ jkItem.cameraname }}</span>
                <span :class="jkItem.status == 1 ? 'jk-item-online' : 'jk-item-offline'">
                  {{ jkItem.status == 1 ? '在线' : '离线' }}
                </span>
              </div>
            </van-collapse-item>
          </van-collapse>
        </van-collapse-item>
      </van-collapse>
    </van-popup>
    <van-popup
      v-model="isShowJKPopup"
      :style="{
        width: '100%',
        height: '100%',
        paddingTop: `${statusBarHeight}px`,
        boxSizing: 'border-box'
      }">
      <ComH5Player
        ref="h5Player"
        v-if="isShowJKPopup"
        :previewUrl="previewUrl"
        @closePlayer="closePlayer"></ComH5Player>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ComOpenlayersMap from '../../components/com-openlayers-map.vue'
import ComH5Player from '../../components/com-h5-player.vue'
import { getCamerasList, previewURLs } from '@/api'

export default {
  components: { ComOpenlayersMap, ComH5Player },
  data() {
    return {
      olMap: null,
      olView: null,
      layerMap: null,
      jkOnlineStyle: null,
      jkOfflineStyle: null,
      jkSelectedStyle: null,
      statusBarHeight: 24,
      showLayerPopover: false,
      layerType: 'YX', //YX 影像底图 SL 矢量底图
      mapOverlayList: [],
      preJKFeature: null,
      currentKSFeature: null,
      chooseJKFeatures: [],
      currentJKTbbsm: '',
      showJKTBDialog: false,
      jkList: [],
      isShowKSListPopup: false,
      jkListActiveNames: [],
      companyListActiveNames: [],
      expandImg: require('../../assets/ic_expand.png'),
      collapseImg: require('../../assets/ic_collapse.png'),
      isShowJKPopup: false,
      previewUrl: ''
    }
  },
  computed: {
    ...mapGetters(['getNativeApi', 'getNativeCallJs', 'getUserInfo'])
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getNativeCallJs.registerNativieGoBack(() => {
        vm.goBack()
      })
    })
  },
  created() {
    this.setStatusBarState()
    this.getJKList()
  },
  methods: {
    setStatusBarState() {
      this.getNativeApi.setStatusBarColor('#FFFFFF')
      this.getNativeApi.setStatusBarLightMode(true)
      this.getNativeApi.getStatusBarHeight().then(result => {
        this.statusBarHeight = result.data
      })
    },
    mapInited(map, view) {
      this.olMap = map
      this.olView = view
      this.layerMap = this.$refs.map.getLayerMap()

      this.$refs.map.addSingleClick(e => {
        const features = this.olMap.getFeaturesAtPixel(e.pixel, {
          hitTolerance: 30
        })
        if (features.length == 0) {
          return
        }
        const jkFeature = features.filter(item => item.get('layername') == 'JKSHAPE')

        if (jkFeature.length <= 0) {
          return
        } else if (jkFeature.length == 1) {
          this.playJKVideoByFeature(jkFeature[0])
        } else {
          this.chooseJKFeatures = jkFeature.map(feature => {
            const properties = feature.getProperties()
            return {
              feature: feature,
              cameraname: properties['cameraname'],
              cameraindexcode: properties['cameraindexcode']
            }
          })
          this.showJKTBDialog = true
        }
      })
      this.$refs.map.changeResolution(() => {
        const zoom = this.olView.getZoom()
        if (zoom < 10) {
          this.togglemapOverlay(true)
          this.layerMap['JKSHAPE'].setVisible(false)
          this.layerMap['XZQSHAPE'].setVisible(true)
        } else {
          this.togglemapOverlay(false)
          this.layerMap['JKSHAPE'].setVisible(true)
          this.layerMap['XZQSHAPE'].setVisible(false)
        }
      })
      this.drawXZQShape()
    },
    // 在地图上绘制带有背景图的区域
    drawRegionsOnMap() {
      this.mapOverlayList = []
      this.jkList.forEach(item => {
        // 获取template中预定义的元素
        const element = document.getElementById(`region-${item.xzqdm}`)
        // 创建覆盖物
        const overlay = this.$refs.map.createOverlay(element, [item.longitude, item.latitude], {
          positioning: 'bottom-center',
          offset: [0, 20] // 调整位置，使其显示在点的上方
        })
        // 将覆盖物添加到地图
        this.olMap.addOverlay(overlay)
        this.mapOverlayList.push(overlay)
      })
    },

    // 清除地图上的区域
    togglemapOverlay(visible = false) {
      this.mapOverlayList.forEach(item => {
        // item.setVisible(visible)
        item.setMap(visible ? this.olMap : null)
      })
    },
    drawXZQShape() {
      for (const xzqItem of this.getUserInfo.wkt) {
        const feature = this.$refs.map.createXZQFeature(xzqItem.wkt)
        feature.setProperties(xzqItem)
        feature.setId(xzqItem.xdm)
        feature.set('layername', 'XZQSHAPE')
        const defalutStyle = this.$refs.map.getXZQDefalutStyle()
        feature.setStyle(defalutStyle)
        this.layerMap['XZQSHAPE'].getSource().addFeature(feature)
      }
    },
    drawJKShape() {
      for (const xzqItem of this.jkList) {
        for (const companyItem of xzqItem.children) {
          for (const jkItem of companyItem.children) {
            if (jkItem.longitude == 0.0 || jkItem.latitude == 0.0) {
              continue
            }
            const feature = this.$refs.map.createJKFeature([jkItem.longitude, jkItem.latitude])
            feature.setProperties(jkItem)
            feature.setId(jkItem.cameraindexcode)
            feature.set('layername', 'JKSHAPE')

            if (jkItem.status == 1) {
              const jkOnlineStyle = this.$refs.map.getJKOnlineStyle(jkItem.cameraname)
              feature.setStyle(jkOnlineStyle)
            } else {
              const jkOfflineStyle = this.$refs.map.getJKOfflineStyle(jkItem.cameraname)
              feature.setStyle(jkOfflineStyle)
            }
            this.layerMap['JKSHAPE'].getSource().addFeature(feature)
          }
        }
      }
    },
    changeBaseLayer(layerType) {
      if (this.layerType == layerType) {
        return
      }
      this.layerType = layerType
      this.$refs.map.changeBaseLayer(layerType)
    },
    openLayerPopover() {
      this.showLayerPopover = true
    },
    positionSelf() {
      this.$refs.map.positionSelf()
    },
    jurisdiction() {
      const xzqInfo = this.getUserInfo.hcqy
      this.$refs.map.jurisdiction(xzqInfo.minx, xzqInfo.maxx, xzqInfo.miny, xzqInfo.maxy)
    },
    goBack() {
      if (this.isShowJKPopup) {
        this.$refs.h5Player.closePlayer()
      } else {
        this.$router.go(-1)
      }
    },
    onJKConfirm() {
      if (this.currentJKTbbsm == '') {
        this.$toast('请选择目标监控设备')
        return
      }
      const featureItem = this.chooseJKFeatures.find(featureItem => featureItem.cameraindexcode == this.currentJKTbbsm)
      this.playJKVideoByFeature(featureItem.feature)
      this.currentJKTbbsm = ''
    },
    getJKList() {
      const params = {}
      getCamerasList(params)
        .then(res => {
          this.jkList = res.data
          setTimeout(() => {
            this.drawRegionsOnMap()
            this.drawJKShape()
          }, 500)
        })
        .catch(err => {
          console.log('获取矿山列表失败')
        })
    },

    toStatistics() {},
    openJKList() {
      this.isShowKSListPopup = true
    },
    jkItemClick(jkItem) {
      this.isShowKSListPopup = false
      const jkFeature = this.layerMap['JKSHAPE'].getSource().getFeatureById(jkItem.cameraindexcode)
      if (jkFeature) {
        this.playJKVideoByFeature(jkFeature)
      } else {
        this.playJKVideoByJKItem(jkItem)
      }
    },
    playJKVideoByFeature(feature) {
      if (this.preJKFeature) {
        const preProperties = this.preJKFeature.getProperties()
        this.preJKFeature.setStyle(this.$refs.map.getJKOnlineStyle(preProperties['cameraname']))
      }
      const properties = feature.getProperties()
      feature.setStyle(this.$refs.map.getJKSelectedStyle(properties['cameraname']))
      this.preJKFeature = feature
      this.olView.animate({ zoom: 16, center: [properties['longitude'], properties['latitude']], duration: 600 })

      if (properties['status'] != 1) {
        this.$toast('该监控已离线,暂时无法播放')
        return
      }
      const params = { cameraIndexCode: properties['cameraindexcode'], streamType: 0, protocol: 'ws', transmode: 1 }
      previewURLs(params)
        .then(res => {
          this.previewUrl = res.data
          this.isShowJKPopup = true

          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })
    },
    playJKVideoByJKItem(jkItem) {
      if (jkItem['status'] != 1) {
        this.$toast('该监控已离线,暂时无法播放')
        return
      }
      const params = { cameraIndexCode: jkItem['cameraindexcode'], streamType: 0, protocol: 'ws', transmode: 1 }
      previewURLs(params)
        .then(res => {
          this.previewUrl = res.data
          this.isShowJKPopup = true

          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })
    },
    closePlayer() {
      this.isShowJKPopup = false
    }
  }
}
</script>

<style lang="scss" scoped>
.jksb-container {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.navbar {
  width: calc(100vw - 24px);
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgb(0, 0, 0, 0.1);
  padding: 0 12px;
}
.navbar-title {
  font-weight: 800;
  font-size: 18px;
  color: #ffffff;
}
.navbar-right-text {
  font-size: 14px;
  color: #ffffff;
}
.top-left {
  position: absolute;
  top: 5.375rem;
  left: 0.625rem;
}
.top-right {
  position: absolute;
  top: 5.375rem;
  right: 0.625rem;
}
.left-bottom {
  position: absolute;
  left: 0.625rem;
  bottom: 3.625rem;
}
.right-bottom {
  position: absolute;
  right: 0.625rem;
  bottom: 3.625rem;
}
.btn-icon-group {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.btn-icon {
  width: 3rem;
  height: 3rem;
  margin-bottom: 0.5rem;
  background: #fff;
  border-radius: 0.375rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.icon-name {
  font-size: 0.625rem;
  color: #333;
  height: 0.9375rem;
  line-height: 0.9375rem;
  margin-top: 0.0625rem;
}
.layer-box {
  padding: 3px 5px;
}
.layer-sl {
  margin-left: 5px;
}
/* 区域覆盖物样式 */
.region-container {
  background-size: 100% 100%;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  backdrop-filter: blur(20px);
  width: 80px;
  height: 40px;
  border: 1px solid RGBA(144, 184, 206, 0.8);
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  .region-xzqmc {
    font-size: 10px;
    color: #ffffffb3;
  }
  .region-icon {
    width: 20px;
    height: 20px;
    margin-right: 6px;
  }
  .region-count {
    font-size: 14px;
    margin-top: 2px;
    color: #fff;
    font-weight: 700;
  }
}
::v-deep .van-collapse-item__title {
  display: flex;
  align-items: center;
}
::v-deep .van-cell__left-icon {
  display: flex;
  align-items: center;
  padding-bottom: 2px;
}
::v-deep .van-cell__title {
  display: flex;
  align-items: center;
}
::v-deep .van-cell__right-icon {
  display: none;
}
::v-deep .van-collapse-item__content {
  padding: 0 3px 0 16px;
}
.company-item ::v-deep .van-cell__value {
  -webkit-box-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  overflow: visible;
}
.company-item ::v-deep .van-cell {
  padding: 10px 14px 10px 10px;
}
.jk-item {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #efeff4;
  .jk-item-name {
    font-size: 14px;
    color: #666;
  }
}
.jk-item-online {
  padding: 3px 20px;
  background-color: rgba(0, 216, 244, 0.15);
  border-radius: 16px;
  font-size: 12px;
  color: #00d8f4;
}
.jk-item-offline {
  padding: 3px 20px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 16px;
  font-size: 12px;
  color: #999999;
}
</style>
